package com.jackrain.clouddata.oms.dao;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.util.TypeUtils;
import com.jackrain.nea.core.db.Tools;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.web.query.QueryEngine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * By Bigzhi
 */

@Slf4j
@Transactional
@Component
public class RetSaleDao {
    public void insertRetSale(JSONArray paramArray, String tag){
        log.info("============insertRetSale=============");

        //根据tag获取公司ID
        String clientIdSql = "SELECT AD_CLIENT_ID FROM OMS_TAG WHERE ISACTIVE='Y' AND TAGNAME = ?";
        JSONObject clientJson = QueryEngine.getInstance().doQueryObject(clientIdSql,new Object[]{tag});
        if (clientJson == null){
            throw new NDSException("公司ID未找到!");
        }
        Long clientId = clientJson.getLong("AD_CLIENT_ID");

        boolean insertRetSale = false;

        String insertRetSaleSql=null;
        String insertItemSql=null;

        for (int i=0;i<paramArray.size();i++){

            JSONObject retSaleJson = paramArray.getJSONObject(i);

            String retSaleTableName = retSaleJson.getString("name");
            JSONObject retSaleValueJson = retSaleJson.getJSONObject("value");
            JSONArray itemArray = retSaleJson.getJSONArray("item");

            JSONObject omsRetSaleJson = JSON.parseObject(JSON.toJSONString(retSaleValueJson,new SerializerFeature[]{SerializerFeature.WriteMapNullValue}), Feature.OrderedField);

            for (int l = 0; l < omsRetSaleJson.keySet().size(); l++) {
                String key = (String) omsRetSaleJson.keySet().toArray()[l];
                if (key.contains("DATE") && omsRetSaleJson.get(key) != null) {
                    omsRetSaleJson.put(key, TypeUtils.castToDate(omsRetSaleJson.get(key)));
                }
            }
//          omsRetSaleJson.put("MODIFIEDDATE",new Timestamp(System.currentTimeMillis()));
            omsRetSaleJson.put("AD_CLIENT_ID",clientId);

            String selectRetSaleSql = "SELECT COUNT(1) FROM "+retSaleTableName+" WHERE AD_CLIENT_ID=? AND BILLNO=?";

            //去重
            int count = QueryEngine.getInstance().doQueryInt(selectRetSaleSql, new Object[]{omsRetSaleJson.getInteger("AD_CLIENT_ID"),omsRetSaleJson.getString("BILLNO")});
            if(count < 1){
                //插主表
                omsRetSaleJson.put("ID", Tools.getSequence(retSaleTableName));  //ID

                //生成insertRetSaleSql语句
                if(!insertRetSale){
                    StringBuffer sb = new StringBuffer( "INSERT INTO "+retSaleTableName+ "(" );//insertRetSaleSql语句
                    StringBuffer q = new StringBuffer();//占位符？

                    for (String s : omsRetSaleJson.keySet()) {
                        if(s.equals("ID")){
                            q.append( "?" );
                            sb.append( s +") VALUES(" + q.toString() + ")" );
                        }else{
                            sb.append( s + "," );
                            q.append( "?," );
                        }
                    }
                    insertRetSaleSql = sb.toString();
                    insertRetSale = true;
                }
                //执行主表插入操作,单条插入
                QueryEngine.getInstance().executeUpdate(insertRetSaleSql,omsRetSaleJson.values().toArray());//单条插入主表

                if(itemArray != null && itemArray.size()>0){ //判空 和 size
                    //插子表
                    for(int j=0; j<itemArray.size(); j++){
                        JSONArray insertItemArray = new JSONArray();//批量插入子参数

                        JSONObject itemJson = itemArray.getJSONObject(j);

                        String itemTableName = itemJson.getString("name");
                        JSONArray itemValueArray = itemJson.getJSONArray("value");

                        if(itemValueArray != null && itemValueArray.size()>0){ //判空 和 size
                            boolean insertItem = false;
                            for(int k=0; k<itemValueArray.size(); k++){
                                JSONObject itemValueJson = itemValueArray.getJSONObject(k);
                                JSONObject omsItemJson = JSON.parseObject(JSON.toJSONString(itemValueJson,new SerializerFeature[]{SerializerFeature.WriteMapNullValue}), Feature.OrderedField);

                                for (int l = 0; l < omsItemJson.keySet().size(); l++) {
                                    String key = (String) omsItemJson.keySet().toArray()[l];
                                    if (key.contains("DATE") && omsItemJson.get(key) != null) {
                                        omsItemJson.put(key, TypeUtils.castToDate(omsItemJson.get(key)));
                                    }
                                }
//                              omsItemJson.put("MODIFIEDDATE",new Timestamp(System.currentTimeMillis()));
                                omsItemJson.put("AD_CLIENT_ID",clientId);
                                omsItemJson.put("ID", Tools.getSequence(itemTableName));  //ID

                                //生成insertItemSql语句
                                if(!insertItem) {
                                    StringBuffer sb = new StringBuffer( "INSERT INTO "+itemTableName+ "(" ); //insertItemSql语句
                                    StringBuffer iq = new StringBuffer(); //占位符？
                                    for (String s : omsItemJson.keySet()) {
                                        if(s.equals("ID")){
                                            iq.append( "?" );
                                            sb.append( s +") VALUES(" + iq.toString() + ")" );
                                        }else{
                                            sb.append( s + "," );
                                            iq.append( "?," );
                                        }
                                    }

                                    insertItemSql = sb.toString();
                                    insertItem = true;
                                }
                                insertItemArray.set(k,omsItemJson);
                            }
                            //执行子表插入操作，批量插入
                            QueryEngine.getInstance().executeBatchUpdate(insertItemSql,insertItemArray);//批量插入子表
                        }
                    }
                }
            }
        }
    }
}
